#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <string.h>

#define N 128

#define errlog(errmsg) do{perror(errmsg); exit(1);}while(0)

int main(int argc, const char *argv[])
{
    int sockfd;
    struct sockaddr_in serveraddr;

    socklen_t addrlen = sizeof(struct sockaddr_in);

    char buf[N] = {};

    //创建套接字
    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        errlog("fail to socket");
    }

    //填充网络信息结构体
    //inet_addr 将点分十进制转化成网络字节
    //htons表示将主机字节序转化成网络字节序
    //atoi 将字符串转化成整型数据
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
    serveraddr.sin_port = htons(atoi(argv[2]));

    //向服务器发送连接请求
    if(connect(sockfd, (struct sockaddr *)&serveraddr, addrlen) < 0)
    {
        errlog("fail to accept");
    }

    //与服务器进行通信
    while(1)
    {
        fgets(buf, N, stdin);
        buf[strlen(buf) - 1] = '\0';

        if(send(sockfd, buf, N, 0) < 0)
        {
            errlog("fail to send");
        }

        if(strncmp(buf, "quit", 4) == 0)
        {
            break;
        }

        if(recv(sockfd, buf, N, 0) < 0)
        {
            errlog("fail to recv");
        }
        printf("%s\n", buf);

    }

    close(sockfd);
    return 0;
}
